<?php

namespace app\api\middleware;

use app\api\facade\Jwt;
use app\common\exception\ApiException;
use app\common\model\SystemUser;
use support\Request;
use Webman\Http\Response;

class JwtAuth
{
    /**
     * JWT认证中间件
     * @param Request $request
     * @param callable $next
     * @return Response
     * @throws ApiException
     */
    public function process(Request $request, callable $next): Response
    {
        $token = $request->header('Authorization');
        if (!$token) {
            throw new ApiException('Token不能为空', 401);
        }
        
        // 去除Bearer前缀
        $token = str_replace(getConfig('api.jwt.prefix') . ' ', '', $token);

        try {
            $jwt = Jwt::verifyToken($token);
            // 验证用户是否存在且状态正常
            if (empty($jwt) || empty($jwt['user_id'])) {
                throw new ApiException('用户信息无效', 401);
            }
            $user = SystemUser::where('id', $jwt['user_id'])->findOrEmpty();
            if ($user->isEmpty()) {
                throw new ApiException('用户不存在', 401);
            }
            
            if ($user->status != 1) {
                throw new ApiException('用户已被禁用', 401);
            }

            $request->user = $user;
            return $next($request);
        } catch (ApiException $e) {
            throw new ApiException($e->getMessage(), 401);
        } catch (\Exception $e) {
            throw new ApiException('Token无效或已过期', 401);
        }
    }
}